package top.kaoshanji.p2ch07a;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.kaoshanji.p2ch07a.support.ReferencedObject;

import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;

/**
 * 代码清单-p2ch07a-218页a：幽灵引用对象的使用示例
 * author kaoshanji
 * ^_^
 * create time 2025/1/20 16:57
 */
public class PhantomReferenceExample01 {

    private static final Logger logger = LogManager.getLogger(PhantomReferenceExample01.class);

    public static void main(String[] args) {
        logger.info("...代码清单-p2ch07a-218页a：幽灵引用对象的使用示例...");

        ReferenceQueue<ReferencedObject> queue = new ReferenceQueue<>();
        ReferencedObject obj = new ReferencedObject();
        PhantomReference<ReferencedObject> phantomRef = new PhantomReference<>(obj, queue);
        obj = null;
        Reference<? extends ReferencedObject> ref = null;
        while ((ref = queue.poll()) == null) {
            System.gc();
        }
        phantomRef.clear();
        System.out.println(ref == phantomRef);
        System.out.println("幽灵引用被清除。");

    }

}
